using System;

namespace Tycho.Parser.Peg {
    public class PrecedenceTermSwapper : IAssociationSwapper {
        public CompositeTerm Swap (CompositeTerm outerCompositeTerm) {
            if (outerCompositeTerm is InfixCompositeTerm) {
                var outer = outerCompositeTerm as InfixCompositeTerm;
                
                if (outer.Last is InfixCompositeTerm) {
                    var inner = outer.Last as InfixCompositeTerm;

                    if (outer.Precedence.IsGreaterThan (inner.Precedence)) {
                        return ActuallySwap (outer, inner);
                    }
                }
            }

            return outerCompositeTerm;
        }

        private static CompositeTerm ActuallySwap (InfixCompositeTerm outer, InfixCompositeTerm inner) {
            outer.Last = inner.First;
            inner.First = outer;

            return inner;
        }
    }
}